{
 "metadata": {},
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Matplotlib: show colormaps\n",
      "======================================================================\n",
      "\n",
      "Show Matplotlib colormaps"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#!python\n",
      "from pylab import *\n",
      "from numpy import outer\n",
      "rc('text', usetex=False)\n",
      "a=outer(arange(0,1,0.01),ones(10))\n",
      "figure(figsize=(10,5))\n",
      "subplots_adjust(top=0.8,bottom=0.05,left=0.01,right=0.99)\n",
      "maps=[m for m in cm.datad if not m.endswith(\"_r\")]\n",
      "maps.sort()\n",
      "l=len(maps)+1\n",
      "for i, m in enumerate(maps):\n",
      "    subplot(1,l,i+1)\n",
      "    axis(\"off\")\n",
      "    imshow(a,aspect='auto',cmap=get_cmap(m),origin=\"lower\")\n",
      "    title(m,rotation=90,fontsize=10)\n",
      "savefig(\"colormaps.png\",dpi=100,facecolor='gray')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "![](files/attachments/Matplotlib_Show_colormaps/colormaps3.png)\n",
      "\n",
      "But, what if I think those colormaps are ugly? Well, just make your own\n",
      "using matplotlib.colors.!LinearSegmentedColormap.\n",
      "\n",
      "First, create a script that will map the range (0,1) to values in the\n",
      "RGB spectrum. In this dictionary, you will have a series of tuples for\n",
      "each color 'red', 'green', and 'blue'. The first elements in each of\n",
      "these color series needs to be ordered from 0 to 1, with arbitrary\n",
      "spacing inbetween. Now, consider (0.5, 1.0, 0.7) in the 'red' series\n",
      "below. This tuple says that at 0.5 in the range from (0,1) , interpolate\n",
      "from below to 1.0, and above from 0.7. Often, the second two values in\n",
      "each tuple will be the same, but using diferent values is helpful for\n",
      "putting breaks in your colormap. This is easier understand than might\n",
      "sound, as demonstrated by this simple script:"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#!python\n",
      "from pylab import *\n",
      "cdict = {'red': ((0.0, 0.0, 0.0),\n",
      "                 (0.5, 1.0, 0.7),\n",
      "                 (1.0, 1.0, 1.0)),\n",
      "         'green': ((0.0, 0.0, 0.0),\n",
      "                   (0.5, 1.0, 0.0),\n",
      "                   (1.0, 1.0, 1.0)),\n",
      "         'blue': ((0.0, 0.0, 0.0),\n",
      "                  (0.5, 1.0, 0.0),\n",
      "                  (1.0, 0.5, 1.0))}\n",
      "my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)\n",
      "pcolor(rand(10,10),cmap=my_cmap)\n",
      "colorbar()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "![](files/attachments/Matplotlib_Show_colormaps/cmap_example.png)\n",
      "\n",
      "As you see, the colormap has a break halfway through. Please use this\n",
      "new power responsibly.\n",
      "\n",
      "Here a slightly modified version of the above code which allows for\n",
      "displaying a selection of the pre-defined colormaps as well as\n",
      "self-created registered colormaps. Note that the cmap\\_d dictionary in\n",
      "the cm module is not documented. The choice of indexed colors in\n",
      "discrete\\_cmap is somewhat haphazardous..."
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "\"\"\"Python colormaps demo\n",
      "\n",
      "includes:\n",
      "examples for registering own color maps\n",
      "utility for showing all or selected named colormaps including self-defined ones\"\"\"\n",
      "\n",
      "\n",
      "import matplotlib\n",
      "import matplotlib.colors as col\n",
      "import matplotlib.cm as cm\n",
      "import matplotlib.pyplot as plt\n",
      "import numpy as np\n",
      "\n",
      "\n",
      "def register_own_cmaps():\n",
      "    \"\"\"define two example colormaps as segmented lists and register them\"\"\"\n",
      "    # a good guide for choosing colors is provided at\n",
      "    # http://geography.uoregon.edu/datagraphics/color_scales.htm\n",
      "    #\n",
      "    # example 1:\n",
      "    # create own colormap from purple, blue, green, orange to red\n",
      "    # cdict contains a tuple structure for 'red', 'green', and 'blue'.\n",
      "    # Each color has a list of (x,y0,y1) tuples, where\n",
      "    # x defines the \"index\" in the colormap (range 0..1), y0 is the\n",
      "    # color value (0..1) left of x, and y1 the color value right of x.\n",
      "    # The LinearSegmentedColormap method will linearly interpolate between\n",
      "    # (x[i],y1) and (x[i+1],y0)\n",
      "    # The gamma value denotes a \"gamma curve\" value which adjusts the brightness\n",
      "    # at the bottom and top of the colormap. According to matlab documentation\n",
      "    # this means:\n",
      "    # colormap values are modified as c^gamma, where gamma is (1-beta) for\n",
      "    # beta>0 and 1/(1+beta) for beta<=0\n",
      "    cdict = {'red': ((0.0, 0.0, 0.0),\n",
      "                     (0.3, 0.5, 0.5),\n",
      "                     (0.6, 0.7, 0.7),\n",
      "                     (0.9, 0.8, 0.8),\n",
      "                     (1.0, 0.8, 0.8)),\n",
      "         'green': ((0.0, 0.0, 0.0),\n",
      "                   (0.3, 0.8, 0.8),\n",
      "                   (0.6, 0.7, 0.7),\n",
      "                   (0.9, 0.0, 0.0),\n",
      "                   (1.0, 0.7, 0.7)),\n",
      "         'blue': ((0.0, 1.0, 1.0),\n",
      "                  (0.3, 1.0, 1.0),\n",
      "                  (0.6, 0.0, 0.0),\n",
      "                  (0.9, 0.0, 0.0), \n",
      "                  (1.0, 1.0, 1.0))}\n",
      "    cmap1 = col.LinearSegmentedColormap('my_colormap',cdict,N=256,gamma=0.75)\n",
      "    cm.register_cmap(name='own1', cmap=cmap1)\n",
      "\n",
      "    # example 2: use the \"fromList() method\n",
      "    startcolor = '#586323'  # a dark olive \n",
      "    midcolor = '#fcffc9'    # a bright yellow\n",
      "    endcolor = '#bd2309'    # medium dark red\n",
      "    cmap2 = col.LinearSegmentedColormap.from_list('own2',[startcolor,midcolor,endcolor])\n",
      "    # extra arguments are N=256, gamma=1.0\n",
      "    cm.register_cmap(cmap=cmap2)\n",
      "    # we can skip name here as it was already defined \n",
      "\n",
      "\n",
      "def discrete_cmap(N=8):\n",
      "    \"\"\"create a colormap with N (N<15) discrete colors and register it\"\"\"\n",
      "    # define individual colors as hex values\n",
      "    cpool = [ '#bd2309', '#bbb12d', '#1480fa', '#14fa2f', '#000000',\n",
      "              '#faf214', '#2edfea', '#ea2ec4', '#ea2e40', '#cdcdcd',\n",
      "              '#577a4d', '#2e46c0', '#f59422', '#219774', '#8086d9' ]\n",
      "    cmap3 = col.ListedColormap(cpool[0:N], 'indexed')\n",
      "    cm.register_cmap(cmap=cmap3)\n",
      "\n",
      "    \n",
      "def show_cmaps(names=None):\n",
      "    \"\"\"display all colormaps included in the names list. If names is None, all\n",
      "defined colormaps will be shown.\"\"\"\n",
      "    # base code from http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps\n",
      "    matplotlib.rc('text', usetex=False)\n",
      "    a=np.outer(np.arange(0,1,0.01),np.ones(10))   # pseudo image data\n",
      "    f=plt.figure(figsize=(10,5))\n",
      "    f.subplots_adjust(top=0.8,bottom=0.05,left=0.01,right=0.99)\n",
      "    # get list of all colormap names\n",
      "    # this only obtains names of built-in colormaps:\n",
      "    maps=[m for m in cm.datad if not m.endswith(\"_r\")]\n",
      "    # use undocumented cmap_d dictionary instead\n",
      "    maps = [m for m in cm.cmap_d if not m.endswith(\"_r\")]\n",
      "    maps.sort()\n",
      "    # determine number of subplots to make\n",
      "    l=len(maps)+1\n",
      "    if names is not None: l=len(names)  # assume all names are correct!\n",
      "    # loop over maps and plot the selected ones\n",
      "    i=0\n",
      "    for m in maps:\n",
      "        if names is None or m in names:\n",
      "            i+=1\n",
      "            ax = plt.subplot(1,l,i)\n",
      "            ax.axis(\"off\")\n",
      "            plt.imshow(a,aspect='auto',cmap=cm.get_cmap(m),origin=\"lower\")\n",
      "            plt.title(m,rotation=90,fontsize=10,verticalalignment='bottom')\n",
      "    plt.savefig(\"colormaps.png\",dpi=100,facecolor='gray')\n",
      "\n",
      "\n",
      "\n",
      "if __name__ == \"__main__\":\n",
      "    register_own_cmaps()\n",
      "    discrete_cmap(8)\n",
      "    show_cmaps(['indexed','Blues','OrRd','PiYG','PuOr',\n",
      "                'RdYlBu','RdYlGn','afmhot','binary','copper',\n",
      "                'gist_ncar','gist_rainbow','own1','own2'])"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}